package model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class Biblioteca {
	
    private static DocumentBuilderFactory dbfac;
    private static DocumentBuilder docBuilder;
    private static TransformerFactory transfac;
    private static Transformer trans;
    private static File arquivo;
	
	public static int geraRandom(int inicio, int fim){
		Random rand = new Random();
			
		if ( inicio > fim )
			throw new IllegalArgumentException("Inicio nao pode ser maior que o Fim.");
		
		long intervalo = (long)fim - (long)inicio + 1;
		    
		return (int)((long)(intervalo * rand.nextDouble()) + inicio);
	}
	
	public static void inicializaXML(){
		try {
			dbfac = DocumentBuilderFactory.newInstance();
			docBuilder = dbfac.newDocumentBuilder();
            transfac = TransformerFactory.newInstance();
            trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Document criaDocumentoXML(){
		return docBuilder.newDocument();
	}
	
	public static Document criaDocumentoXML(String nomeArquivo) throws SAXException, IOException{
		arquivo = new File(nomeArquivo);
		return docBuilder.parse(arquivo);
	}
	
	public static void salvaDocumentoXML(Document doc, String nomeArquivo){
        try {
        	FileOutputStream fos = new FileOutputStream(nomeArquivo);
            StreamResult result = new StreamResult(fos);
            DOMSource source = new DOMSource(doc);
			trans.transform(source, result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	
}
